package com.jboltai.util.text;

import com.jboltai.config.JBoltAIConfig;
import com.jboltai.event.text.TextEvent;
import org.apache.tika.sax.ContentHandlerDecorator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;

import java.util.function.Consumer;

public class ChunkContentHandler extends ContentHandlerDecorator {
    protected static final Logger LOGGER = LoggerFactory.getLogger(JBoltAIConfig.LOGGER_NAME);
    private static final String TAG_P = "p";
    private static final String SEPARATOR = "\n";

    private Consumer<String> consumer;

    private TextEvent event;

    private boolean hasContent = false;

    private String temp;

    public ChunkContentHandler(Consumer<String> consumer) {
        if (consumer == null) {
            throw new IllegalArgumentException("consumer can not be null");
        }
        this.consumer = consumer;
    }

    public ChunkContentHandler(Consumer<String> consumer, TextEvent event) {
        if (consumer == null) {
            throw new IllegalArgumentException("consumer can not be null");
        }
        this.consumer = consumer;
        this.event = event;
    }


    @Override
    public void characters(char[] ch, int start, int length) {
        temp = new String(ch, start, length);
        consumer.accept(temp);
        if (length > 0 && temp.equals(SEPARATOR) == false) {
            hasContent = true;
        }
    }

    public void endElement(String uri, String localName, String name) throws SAXException {
        super.endElement(uri, localName, name);
        if (TAG_P.equals(localName) && hasContent) {
            consumer.accept(SEPARATOR);
        }
    }
}
